﻿using H2.NET.Business;
using H2.NET.Data.Common;
using H2.NET.Web.Pages.SMD.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Web.UI.WebControls;
using AutoMapper;
using H2.NET.Business.Core;
using H2.NET.Common;
using H2.NET.DBUtility;
using Ultimus.WFServer;
using Newtonsoft.Json;

namespace H2.NET.Web.Pages.SMD.Service
{
    public static class BusinessService
    {
        #region 每次发起小流程自动插入子流程表
        public static void SaveChildProcess(TaskAPI taskAPI, t_Assessment ass, string status, string reason = "", DateTime? time = null, string username = "")
        {
            var childProcess = getChildProcessByPI(taskAPI);
            if (childProcess == null)
            {
                childProcess = new t_smd_ChildProcess
                {
                    Incident = taskAPI.Incident,
                    Process = taskAPI.Process,
                    BusinessProcess = ass.BusinessProcess,
                    BusinessKey = ass.BusinessKey,
                    Status = status,
                    AbortReason = reason,
                    AbortTime = time
                };
            }
            else
            {
                childProcess.Status = status;
            }
            childProcess.AbortTime = time;
            childProcess.AbortReason = reason;
            childProcess.AbortUser = username;
            Storage.Save(childProcess);
        }

        public static void SaveChildProcess(string process, int incident, string status, DateTime? time = null, string username = "")
        {
            var childProcess = (t_smd_ChildProcess._Process == process & t_smd_ChildProcess._Incident == incident).ListFirst<t_smd_ChildProcess>();

            childProcess.Status = status;
            childProcess.AbortTime = time;
            childProcess.AbortReason = "";
            childProcess.AbortUser = username;
            Storage.Save(childProcess);
        }
        #endregion

        #region 每次发起小流程自动插入子流程表
        public static void SaveChildProcess(TaskAPI taskAPI, t_Assessment ass, string status, string reason, DateTime time)
        {
            var childProcess = getChildProcessByPI(taskAPI);
            if (childProcess == null)
            {
                childProcess = new t_smd_ChildProcess
                {
                    Incident = taskAPI.Incident,
                    Process = taskAPI.Process,
                    BusinessProcess = ass.BusinessProcess,
                    BusinessKey = ass.BusinessKey,
                    Status = status,
                    AbortReason = reason,
                    AbortTime = time
                };
            }
            else
            {
                childProcess.Status = status;
            }

            Storage.Save(childProcess);
        }
        #endregion

        #region 获取子流程
        public static t_smd_ChildProcess getChildProcessByPI(TaskAPI taskAPI)
        {
            var childProcess = (t_smd_ChildProcess._Process == taskAPI.Process & t_smd_ChildProcess._Incident == taskAPI.Incident).ListFirst<t_smd_ChildProcess>();
            return childProcess;
        }
        #endregion

        #region 根据业务流程号驳回数据,还原数据
        public static void AbortByBusinesskey(string businessKey, string reason)
        {
            //更新子流程表
            var sql = string.Format("update {0}.DBO.t_smd_childprocess set status = 'abort',aborttime='" + DateTime.Now.ToString("yyyy-MM-dd") + "',abortreason = '" + reason + "',abortuser ='张佩华' where businesskey ='" + businessKey + "'", DbHelperSQL.GetDatabaseName("oleDB"));
            DbHelperSQL.ExecuteSql(sql);
            var list = (t_smd_ChildProcess._BusinessKey == businessKey).List<t_smd_ChildProcess>();

            //驳回流程
            foreach (var process in list)
            {
                var incident = new Incident();

                if (!incident.LoadIncident(process.Process, process.Incident))
                {
                    continue;
                }

                var strError = "";
                //执行任务取消
                var flag = incident.AbortIncident(incident.strIncidentOwner, DateTime.Now.ToString("yyyy-MM-dd"), out strError);
                if (strError != "")
                {
                    var strSql = new StringBuilder();
                    strSql.Append(string.Format("UPDATE {0}.dbo.INCIDENTS SET STATUS=@Status, ENDTIME=@EndTime ", DbHelperSQL.GetDatabaseName("bpmDB")));
                    strSql.Append("WHERE PROCESSNAME=@Process AND INCIDENT=@Incident");
                    SqlParameter[] parameters = {
					                new SqlParameter("@Process", SqlDbType.VarChar,50),
					                new SqlParameter("@Incident", SqlDbType.Int,4),
					                new SqlParameter("@Status", SqlDbType.Int,4),
                                    new SqlParameter("@EndTime", SqlDbType.DateTime)
                            };
                    parameters[0].Value = process.Process;
                    parameters[1].Value = process.Incident;
                    parameters[2].Value = 1;
                    parameters[3].Value = DateTime.Now;
                    DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
                    strError = "";
                    incident.AbortIncident(incident.strIncidentOwner, DateTime.Now.ToString("yyyy-MM-dd"), out strError);


                }

                if (strError == "")
                {
                    var incidentManageLog = new t_log_IncidentManage
                    {
                        Process = incident.strProcessName,
                        Incident = incident.nIncidentNo,
                        Status = true,
                        Action = "取消实例",
                        Description = "取消实例（" + incident.nIncidentNo + "）" + (strError == "" ? "成功" : "失败"),
                        Creator = "",
                        CreateOn = DateTime.Now
                    };
                    Storage.Save(incidentManageLog);
                }
            }
            //还原数据
            var restoreSql = string.Format("{0}.dbo.[itssRestoreData] '" + businessKey + "'", DbHelperSQL.GetDatabaseName("smdDB"));
            DbHelperSQL.ExecuteSql(restoreSql);
        }
        #endregion

        #region 插入流程变量
        public static void saveProcessRelation(TaskAPI taskAPI, t_Assessment ass, t_smd_Store store, t_smd_Device device, t_smd_Dealer dealer, t_smd_Dealer oldDealer, List<t_smd_Store> stores, List<t_smd_Device> devices, List<t_smd_Dealer> dealers)
        {
            var relation = getRelationByPI(ass.BusinessKey);
            if (relation == null)
            {
                relation = new t_smd_Relation
                {
                    Process = taskAPI.Process,
                    Incident = taskAPI.Incident,
                    BusinessKey = ass.BusinessKey,
                    BusinessProcess = ass.BusinessProcess,
                };
            }

            if (store != null)
            {
                relation.StoreName = store.StoreName;
                relation.StoreID = store.StoreID.ToString();
                relation.AuthID = store.AuthID;
                relation.City = store.CityName;
                relation.StoreStatus = store.StoreStatus;
                relation.StoreType = store.StoreType;
                relation.Region = store.Region;
                relation.Province = store.Province;
                if (string.IsNullOrEmpty(relation.EapproveSN))
                {
                    relation.EapproveSN = store.EapproveSN;
                }
                if (string.IsNullOrEmpty(relation.EapproveData))
                {
                    relation.EapproveData = store.StoreApprovedDate.HasValue ? store.StoreApprovedDate.Value.ToString("yyyy-MM-dd") : ""; ;
                }
            }


            if (device != null)
            {
                relation.DeviceID = device.DeviceID.ToString();
                relation.FullsetSN = device.FullSetSN;
            }

            if (dealer != null)
            {
                relation.DealerID = dealer.DealerID.ToString();
                relation.DealerCode = dealer.DealerCode;
            }

            if (oldDealer != null)
            {
                relation.OldDealerCode = oldDealer.DealerCode;
                relation.OldDealerID = oldDealer.DealerID;
            }
            if (stores != null && stores.Count > 0)
            {
                var storeName = "";
                var StoreID = "";
                var AuthID = "";
                var EapproveSN = "";
                var EapproveData = "";
                var storeStatus = "";
                var storeType = "";

                for (int i = 0; i < stores.Count; i++)
                {
                    storeName += stores[i].StoreName;
                    StoreID += stores[i].StoreID;
                    AuthID += stores[i].AuthID;
                    storeStatus += stores[i].StoreStatus;
                    storeType += stores[i].StoreType;

                    EapproveSN += stores[i].EapproveSN;
                    EapproveData += stores[i].StoreApprovedDate.HasValue ? stores[i].StoreApprovedDate.Value.ToString("yyyy-MM-dd") : "";

                    if (i < stores.Count - 1)
                    {
                        storeName += ",";
                        StoreID += ",";
                        AuthID += ",";
                        EapproveSN += ",";
                        EapproveData += ",";
                        storeType += ",";
                        storeStatus += ",";
                    }
                }
                relation.StoreName = storeName;
                relation.StoreID = StoreID;
                relation.AuthID = AuthID;
                relation.StoreType = storeType;
                relation.StoreStatus = storeStatus;
                relation.City = stores[0].CityName;
                relation.Region = stores[0].Region;
                relation.Province = stores[0].Province;
                relation.EapproveSN = EapproveSN;
                relation.EapproveData = EapproveData;

            }

            if (devices != null && devices.Count > 0)
            {
                var fullset = "";

                for (int i = 0; i < devices.Count; i++)
                {
                    fullset += devices[i].FullSetSN;
                    if (i < devices.Count - 1)
                    {
                        fullset += ",";
                    }
                }

                relation.FullsetSN = fullset;
            }

            if (dealers != null && dealers.Count > 0)
            {
                var dealerID = "";
                var dealerCode = "";
                List<string> regions = new List<string>();
                List<string> Provinces = new List<string>();
                List<string> Citys = new List<string>();
                for (int i = 0; i < dealers.Count; i++)
                {
                    dealerID += dealers[i].DealerID;
                    dealerCode += dealers[i].DealerCode;
                    regions.Add(dealers[i].Region);
                    Provinces.Add(dealers[i].Province);
                    Citys.Add(dealers[i].CityName);
                    if (i < stores.Count - 1)
                    {
                        dealerID += ",";
                        dealerCode += ",";
                    }
                }

                regions = regions.Distinct().ToList<string>();
                Provinces = Provinces.Distinct().ToList<string>();
                Citys = Citys.Distinct().ToList<string>();
                var region = "";
                var province = "";
                var city = "";
                foreach (var _region in regions)
                {
                    region = string.Join(",", _region);
                }
                foreach (var _province in Provinces)
                {
                    province = string.Join(",", _province);
                }
                foreach (var _city in Citys)
                {
                    city = string.Join(",", _city);
                }

                relation.DealerID = dealerID;
                relation.DealerCode = dealerCode;
                relation.Region = region;
                relation.Province = province;
                relation.City = city;
            }
            Storage.Save(relation);
        }
        #endregion

        #region 获取流程关系
        public static t_smd_Relation getRelationByPI(string processKey)
        {
            var relation = (t_smd_Relation._BusinessKey == processKey).ListFirst<t_smd_Relation>();
            return relation;
        }
        #endregion

        #region 更新保证金，执行存储过程
        public static void DepositChange(string fullsetsn, decimal oldDeposit, decimal newDeposit, string reason)
        {
            var sql = string.Format("{0}.dbo.[itssdepositlog] '" + fullsetsn + "'," + oldDeposit + "," + newDeposit + ",'" + reason + "'", DbHelperSQL.GetDatabaseName("smdDB"));
            DbHelperSQL.ExecuteSql(sql);
        }
        #endregion

        #region 根据流程找相应的itss数据

        public static t_smd_Itss GetItssByPi(string process, int incident)
        {
            return (t_smd_Itss._Process == process & t_smd_Itss._Incident == incident).ListFirst<t_smd_Itss>(Storage.Context3, "itssid desc") ?? new t_smd_Itss();
        }

        #endregion

        #region 保存同步信息
        public static void SaveCRMSyncData(t_StoreMasterData masterData, t_smd_Store store, t_smd_Dealer dealer, t_smd_Dealer subDealer = null)
        {
            t_smd_CrmSync crmSync = new t_smd_CrmSync();
            if (!string.IsNullOrEmpty(masterData.SerialNumber))
            {
                string[] array = masterData.SerialNumber.Split('/');
                //序列号
                crmSync.Id = array.Length > 0 ? array[0] : "";
                //parent_id(Eapprove2)
                crmSync.parent_id = array.Length > 1 ? array[1] : "";
            }
            else
            {
                //database the id must have value
                throw new Exception("SerialNumber must have value");
            }
            //门店号
            crmSync.authid = masterData.AuthID;
            //提交日期 
            crmSync.created_at = masterData.SubmitDate;
            //填单人
            crmSync.name = masterData.Creator;
            //门店类型
            crmSync.store_type_id = masterData.StoreType;
            //渠道
            crmSync.primary_an_brand_id = masterData.Channel;
            //门店装修类型
            crmSync.store_decoration_type_id = masterData.NewFitment;
            //区域
            crmSync.region_of_sales_id = store.Region;
            //城市
            crmSync.city = masterData.CityName;
            //区县
            crmSync.district = masterData.District;
            //门店地址
            crmSync.address = masterData.Address;
            //维度
            crmSync.lat = masterData.Lat;
            //经度
            crmSync.lon = masterData.Lon;
            //建材市场编号
            crmSync.bmc_id = masterData.BMCCode; //这个有待商议，因为我们这边应该拿到的是Code和Name
            //联络电话
            crmSync.general_phone = masterData.Telephone;
            //门店建筑面积m2
            crmSync.total_store_m2 = store.StoreSize;
            //门店关闭\降级时间
            crmSync.store_close_date = store.CloseDate;

            //负责销售
            crmSync.owner_id = store.AccountOwner;
            //经销商Id
            crmSync.sap_id = dealer.DealerID.ToString();

            //同步次数
            crmSync.synctimes = 0;
            //创建时间
            crmSync.createdate = DateTime.Now;
            //同步状态
            crmSync.syncstatus = 0; //初始状态

            //调色机型号
            crmSync.dispenser_type_id = masterData.DispenseModel;
            //震荡机型号
            crmSync.shaker_type_id = masterData.ShakerModel;
            //电脑型号
            crmSync.pc_type_id = masterData.PcModel;
            //微信公众号
            crmSync.wechat_id = masterData.WechatId;
            //调色机购机款总额
            crmSync.purchase_cost = masterData.BuyMachineDeposit;
            //调色机保证金余额
            crmSync.tinting_deposit = masterData.MachineDeposit;
            //#region 新加字段 kim.zheng 2016-09-20
            ////门店联系人
            //crmSync.store_contact = masterData.ContractPerson;  
            ////市场/街道全称
            //crmSync.street = masterData.MallName;
            ////市场/街道简称
            //crmSync.street = masterData.MallShortName;
            //yanxiang 2017.07 add
            crmSync.market_name = masterData.MallName;
            crmSync.store_name = store.StoreName;
            //门店开业时间
            crmSync.store_open_date = masterData.OpenDate;
            //目前门店类型开业时间
            crmSync.store_open_date = masterData.CurrentStartDate;
            //门店名称
            crmSync.store_name = masterData.StoreName;
            //关店原因归类,yanxiang:store_close_reason_id需从Log表读取
            //crmSync.store_close_reason_id = store.CloseType;
            //if (logs!=null&&logs.Count() > 0)
            //{
            //    t_StoreDataChangeLog log = logs.Where(c => c.FieldName == "CloseReason").FirstOrDefault();
            //    if (log != null)
            //    {
            //        crmSync.store_close_reason_id = log.AfterValue;
            //    }
            //}
            crmSync.status_id = masterData.Status;
            //tingting id 从t_smd_device获取by AuthID OR StoreID
            var devicer = DeviceService.GetOneByStoreId(store.StoreID);
            if (devicer != null)
            {
                crmSync.tinting_ID = devicer.DispenserFixedAsset;
            }
            crmSync.house_number = store.HouseNumber;
            crmSync.store_approve_date = masterData.StoreApprovedDate;
            crmSync.delivery_type = masterData.ApplicationType;//crm to smd this two fileds have same value.
            crmSync.account_owner = masterData.AccountOwner;

            ////设备状态
            //crmSync.status_id = devicer.Status;
            ////固定资产号
            //crmSync.tinting_ID = devicer.DispenserFixedAsset;
            ////调色机型号
            //crmSync.dispenser_type_id = devicer.DispenserModel;
            ////震荡机型号
            //crmSync.shaker_type_id = devicer.ShakerModel;
            ////电脑型号
            //crmSync.pc_type_id = devicer.PcModel;
            ////调色机购机款总额
            //crmSync.purchase_cost = devicer.BuyMachineDeposit; 
            ////调色机保证金余额
            //crmSync.tinting_deposit = deposit.Amount;
            ////系统完成审批日期
            //crmSync.update_at = masterData.StoreApprovedDate.Value;
            //微信公众号
            crmSync.wechat_id = masterData.WechatId;
            ////是否为翻新
            //crmSync.store_decoration_int = masterData.IsRenew.Value == true ? 1 : 0;
            ////是否为旧机更换
            //crmSync.machine_type = masterData.IsTransferMachine == true ? 1 : 0;
            ////设备安装时间
            //crmSync.created_at = devicer.InstallDate;
            ////门店归属 直营/分销
            //crmSync.Owner_Type = dealer.OwnerType.Value;
            ////最新翻新日期
            //crmSync.last_renovation_date = masterData.LastRenewDate.Value;
            //#endregion
            //Storage.Save(Storage.Context3, crmSync);

        }
        #endregion

        #region 存储crmstoreidmapping,crmtintingmapping,t_smd
        public static void SaveSycnMappingOrBusinesskey(string isRenovation,string isDevice,string businesskey)
        {
            int dtype = -1;
            dtype = isRenovation == "0" && isDevice == "1" ? 1 : isRenovation == "1" && isDevice == "1" ? 2 : 0;
            if (dtype == 1)
            {
                SaveSycnMappingAndBusinesskey(1, businesskey);//chris wang 2017 9.5
                SaveSycnMappingAndBusinesskey(2, businesskey);
                SaveSycnMappingAndBusinesskey(3, businesskey);
            }
            else if (dtype == 2)
            {
                SaveSycnMappingAndBusinesskey(2, businesskey);
            }
            else
            {
                SaveSycnMappingAndBusinesskey(1, businesskey);
                SaveSycnMappingAndBusinesskey(2, businesskey);//chris wang 2017 9.11
                SaveSycnMappingAndBusinesskey(3, businesskey);
            }

        }

        public static void SaveSycnMappingAndBusinesskey(int type,string businesskey)
        {
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("oleDB");
            //var sql = string.Format("{0}.dbo.[NewSaveSycnMappingAndBusinesskey] '" + type + "','" + businesskey + "'", DbHelperSQL.GetDatabaseName("smdDB"));
            /*SqlParameter[] pars = new SqlParameter[]
            {
                new SqlParameter("@type",type),
                new SqlParameter("@@businesskey",businesskey)
            };
            SqlDataReader reader = DbHelperSQL.RunProcedure("SaveSycnMappingAndBusinesskey", pars);
            reader.Close(); 
        }*/
            string sql = string.Empty;
            if (type == 1)
            {
                sql = @"insert into AkzoNobelSMD..t_CrmStoreMapping
		                select 
		                top 1
		                    sd.EapproveSN1,
		                    smd.storeid,
                            case smd.storeid when null then null else getdate() end,
		                    smd.authid
		                    from 
			                    AkzoNobelSMD..t_smd_SmdSyncData  sd WITH (NOLOCK)
		                    inner join
			                    t_StoreMasterData  smd WITH (NOLOCK)
		                    on
			                    smd.SerialNumber = sd.SerialNumber
			                    and smd.businesskey = @businesskey
			                    and smd.Process = 'New Store Application'
                            inner join
                                AkzoNobelSMD..t_CrmStoreMapping csm WITH(NOLOCK)
                            on
                                sd.EapproveSN1 <> csm.CrmStoreID
                                and smd.storeid <> csm.StoreID
                                and smd.AuthID <> csm.AuthID";
            }
            else if (type == 2)
            {
                sql = @"insert into AkzoNobelSMD..t_TingtingDeviceMapping
		                select 
                        top 1		
		                sd.EapproveSN2,
		                td.DeviceID,
                        case td.DeviceID when null then null else getdate() end,
		                td.FullSetSN
		                from 
			                AkzoNobelSMD..t_smd_SmdSyncData  sd WITH(NOLOCK)
		                inner join
			                t_StoreMasterData  smd WITH(NOLOCK)
		                on
			                smd.SerialNumber = sd.SerialNumber
			                and smd.businesskey = @businesskey
			                and smd.Process = 'New Store Application'
		                inner join
			                t_StoreMasterData  smd2 WITH(NOLOCK)
		                on
			                smd.businesskey = smd2.businesskey
			                and smd2.Process = 'New Store Deposit Receive'
		                left join
			                 AkzoNobelSMD..t_smd_Device td WITH(NOLOCK)
		                on
			                td.DeviceID = smd2.DeviceID
                       inner join
                            AkzoNobelSMD..t_TingtingDeviceMapping tdm WITH(NOLOCK)
                       on
                            tdm.CrmTingtingID <> sd.EapproveSN2
                            and tdm.DeviceID <> td.DeviceID
                            and tdm.FullSetSN <> td.FullSetSN";
            }
            else
            {
                sql = @"insert into AkzoNobelSMD..t_smdsyncBusinesskey
		                select 
			                @businesskey,
			                getdate(),
			                -1";
            }

            int Execute = DbHelperSQL.ExecuteSql(sql, new SqlParameter("@businesskey", businesskey));
            
        }
        #endregion
    }
}